<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- gutter="20" 列与列之间的间隔
      :span="8"  具体列的所占有的宽度（24为整个屏幕宽度）-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            :clearable="true"
            @clear="getUserList"
            placeholder="请输入内容"
          >
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="addUser" type="primary">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userlist" style="width: 100%">
        <el-table-column label="序号" type="index" width="80"></el-table-column>
        <el-table-column label="用户名" prop="UserName" width="100"></el-table-column>
        <el-table-column label="手机" prop="Mobile" width="180"></el-table-column>
        <el-table-column label="邮箱" prop="Email" width="180"></el-table-column>
        <el-table-column label="角色" prop="RoleName" width="100"></el-table-column>
        <el-table-column label="状态" prop="MgState" width="100">
          <template slot-scope="a">
            <el-switch
              v-model="a.row.MgState"
              active-color="#409EFF"
              inactive-color="#C0CCDA"
              @change="userStateChanged(a.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="a">
            <el-button type="success" size="mini" @click="updateUser(a.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="deleteUser(a.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-sizes="[3,4,6,10]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      titel="添加用户信息"
      width="40%"
      :visible.sync="addUserDialogVisible"
      @close="addUserDialogClose"
    >
      <el-form ref="addFormRef" :rules="userFormRules" :model="addForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="addUserEnter">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      titel="修改用户信息"
      width="40%"
      :visible.sync="updateUserDialogVisible"
      @close="updateUserDialogClose"
    >
      <el-form ref="updateFormRef" :rules="userFormRules" :model="updateForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="updateForm.password" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="updateForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserEnter">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Home",
  props: [],
  components: {},
  data() {
    // 自定义校验手机号规则
    var checkmobile = (rule, value, callback) => {
      const regMobile = /^1[3456789]\d{9}$/;
      if (regMobile.test(value)) {
        // 合法手机
        callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    // 自定义邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        // 合法手机
        callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    return {
      queryInfo: { pagenum: 1, pagesize: 3, query: "" },
      userlist: [],
      total: 0,
      addUserDialogVisible: false,
      updateUserDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      updateForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        id: ""
      },
      // 校验数据
      userFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度应该在3到5字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度应该在6到15字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkmobile, trigger: "blur" }
        ]
      }
    };
  },
  //方法 函数写这里
  methods: {
    async getUserList() {
      const res = await this.$http.get("/api/users", {
        params: this.queryInfo
      });
      this.userlist = res.data.data;
      this.total = res.data.total;
    },
    //监听pagesize改变的事件
    handleSizeChange(newpagesize) {
      this.queryInfo.pagesize = newpagesize;
      this.getUserList({
        params: this.queryInfo
      });
    },
    //监听pagenum改变的事件
    handleCurrentChange(newpagenum) {
      this.queryInfo.pagenum = newpagenum;
      this.getUserList({
        params: this.queryInfo
      });
    },
    async userStateChanged(userinfo) {
      const res = await this.$http.get("/api/userstate", {
        params: userinfo
      });
      if (res.data.code != 200) {
        this.$message.error("改变用户状态不成功");
        return;
      }
      this.$message.success("用户状态已经改变成功为:" + res.data.newState);
    },
    //查询接口事件
    async search() {
      if (this.queryInfo.query == "") {
        return;
      }
      const res = await this.$http.get("/api/searchuesr", {
        params: this.queryInfo
      });
      console.log(res.data);
      this.userlist = res.data.data;
      this.total = res.data.data.length;
    },
    addUser() {
      this.addUserDialogVisible = true;
    },
    //添加用户点击确定按钮的事件
    addUserEnter() {
      var pagenum = "pagenum";
      var pagenumVal = this.queryInfo.pagenum;
      this.addForm[pagenum] = pagenumVal;
      var pagesize = "pagesize";
      var pagesizeVal = this.queryInfo.pagesize;
      this.addForm[pagesize] = pagesizeVal;

      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const res = await this.$http.get("./api/adduser", {
            params: this.addForm
          });
          this.userlist = res.data.data;
          this.total = res.data.total;
          this.addUserDialogVisible = false;
        }
      });
    },
    //添加用户的对话框在 自身在关闭的时候 会触发  addUserDialogClose函数
    addUserDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    //修改用户的对话框在 自身在关闭的时候 会触发  updateDialogClosed函数
    updateUserDialogClose() {
      this.$refs.updateFormRef.resetFields();
    },
    // 修改用户信息
    updateUser(userinfo) {
      this.updateUserDialogVisible = true;
      this.updateForm.id = userinfo.id;
      this.updateForm.username = userinfo.UserName;
      this.updateForm.password = userinfo.Password;
      this.updateForm.email = userinfo.Email;
      this.updateForm.mobile = userinfo.Mobile;
    },
    // 修改用户后的确定信息
    updateUserEnter() {
      var pagenum = "pagenum";
      var pagenumVal = this.queryInfo.pagenum;
      this.updateForm[pagenum] = pagenumVal;
      var pagesize = "pagesize";
      var pagesizeVal = this.queryInfo.pagesize;
      this.updateForm[pagesize] = pagesizeVal;
      this.$refs.updateFormRef.validate(async valid => {
        if (valid) {
          const res = await this.$http.get("./api/updateuser", {
            params: this.updateForm
          });
          this.userlist = res.data.data;
          this.total = res.data.total;
          this.updateUserDialogVisible = false;
        }
      });
    },
    //删除用户
    async deleteUser(id) {
      const a = await this.$confirm("操作将永久删除用户确定吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => {
        console.log("错误信息err", err);
      });
      if (a != "confirm") {
        this.$message.info("算了先不删");
        return;
      }
      this.queryInfo.id = id;
      const res = await this.$http.get("/api/deleteuser", {
        params: this.queryInfo
      });
      this.$message.info("删除数据成功");
      this.userList = res.data.data;
      this.total = res.data.total;
      this.getUserList();
    }
  },
  //计算属性
  computed: {},
  //侦听器
  watch: {},
  //过滤器
  filters: {},
  //以下是生命周期
  //组件创建之前
  beforeCreate() {},
  //组件创建之后
  created() {
    this.getUserList();
  },
  //页面渲染之前
  beforeMount() {},
  //页面渲染之后
  mounted() {},
  //页面视图数据更新之前
  beforeUpdate() {},
  //页面视图数据更新之后
  updated() {},
  //页面销毁之前
  beforeDestroy() {},
  //页面销毁之后
  destroyed() {}
};
</script>


<style  lang="scss"  scoped >
.el-card {
  margin-top: 15px;
  // height: 100px;
  box-shadow: 0 1px 1px #353333;
}

.el-breadcrumb {
  font-size: 12px;
}
</style>